package com

import com.entity.PackCmd
import com.entity.PackPath
import com.entity.yaml.XmlToTs
import com.languages.LanguagesKit
import com.utils.ScriptUtils
import com.utils.YamlUtil
import com.xmlToTs.XMLtoTS
import extend.error
import extend.runIf
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.kotlin.logger
import picocli.CommandLine
import picocli.CommandLine.Help.Ansi
import kotlin.concurrent.thread

class Main(args: Array<String>) {

    private val packCmd: PackCmd
    private val RESET = "\u001B[0m"
    private val RED = "\u001B[31m"
    private val GREEN = "\u001B[32m"
    private val YELLOW = "\u001B[33m"
    private val BLUE = "\u001B[34m"
    private val PURPLE = "\u001B[35m"
    private val CYAN = "\u001B[36m"
    init {

//        println("\n${RED}=== 开始 ===$RESET")
        packCmd = PackCmd(this::init)

        val colorScheme = CommandLine.Help.defaultColorScheme(Ansi.AUTO)
        val commandLine = CommandLine(packCmd)
            .registerConverter(PackPath::class.java) { PackPath(it) }
            .setColorScheme(colorScheme)

        commandLine.execute(*args)
    }

    private fun init() {
        ScriptUtils.initScript()

        ScriptUtils.script.packCmd = packCmd
        val langConfig = packCmd.languagesConfig
        if (langConfig != null) { // 如果是语言工具
            YamlUtil.loadYaml(langConfig)
            val xmlToTs = YamlUtil.getConfig("xmlToTs", XmlToTs::class)
            if (packCmd.toTs) {
                if (xmlToTs != null) {
                    // xml to ts
                    val id = xmlToTs.startId
                    val readXMLFile = xmlToTs.readXMLPath
                    val writeXMLFile = xmlToTs.writeXMLPath
                    val writeTsFile = xmlToTs.writeTsPath
                    val langConfigDir = langConfig.parent ?: langConfig
                    readXMLFile?.runIf({
                        !it.isAbsolute
                    }) {
                        it.replaceDirectory(langConfigDir.absolutePathString)
                        it.normalize()
                    }
                    writeXMLFile?.runIf({
                        !it.isAbsolute
                    }) {
                        it.replaceDirectory(langConfigDir.absolutePathString)
                        it.normalize()
                    }
                    writeTsFile?.runIf({
                        !it.isAbsolute
                    }) {
                        it.replaceDirectory(langConfigDir.absolutePathString)
                        it.normalize()
                    }

                    val namespaceName = xmlToTs.namespaceName
                    if (readXMLFile != null && writeXMLFile != null && writeTsFile != null) {
                        XMLtoTS().toTS(
                            id ?: 0,
                            readXMLFile,
                            writeXMLFile,
                            writeTsFile,
                            namespaceName
                        )
                    } else {
                        System.err.println("有参数不存在")
                    }
                } else {
                    logger.warn("xml转ts配置文件不存在 或有错误")
                }
            } else {
                // 语言工具处理
                LanguagesKit().start(packCmd)
            }
        } else if (packCmd.stringList?.size == 2) {
            runCatching {
                val scriptFile = PackPath(YamlUtil.getProjectScriptPathMap(packCmd.stringList!![1]))
                if (scriptFile.notExists()) error("不存在文件=${scriptFile.pathString}")

                // 打包环境 1. 内网  2. staging  3. 正式
                YamlUtil.unpackEnvName = packCmd.stringList!![0]

                ScriptUtils.loadFile(scriptFile)
            }.onFailure {
                logger.error(it.message, it)
            }
        } else {
            println(" **********************   打包工具   **********************")
            ScriptUtils.scriptEngine.eval("startScanner()")
        }
    }

}

fun main(args: Array<String>) {
    System.setProperty("java.util.logging.manager", "org.apache.logging.log4j.jul.LogManager");
    System.setProperty("Log4jContextSelector", "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector")
    System.setProperty("LOG_PATH", ScriptUtils.runPath.path)

    // 保证结束前 将日志全部输出完成
    Runtime.getRuntime().addShutdownHook(thread(false) {
        LogManager.shutdown()
    })

    Main(args)
}